package com.sylar.lelepub.tools;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import com.sylar.lelepub.domain.CityInfo;


public class PullParseCityXml {

	public ArrayList<String> root = null;
	public ArrayList<CityInfo> element = null;
	public HashMap<String, ArrayList<CityInfo>> map = null;

	public PullParseCityXml(InputStream is) {

		// 构建XmlPullParserFactory
		try {
			XmlPullParserFactory pullParserFactory = XmlPullParserFactory
					.newInstance();
			// 获取XmlPullParser的实例
			XmlPullParser xmlPullParser = pullParserFactory.newPullParser();
			// 设置输入流 xml文件
			xmlPullParser.setInput(is, "UTF-8");

			// 开始
			int eventType = xmlPullParser.getEventType();
			CityInfo cityInfo = null;
			String mTemp = null;
			try {
				while (eventType != XmlPullParser.END_DOCUMENT) {
					String nodeName = xmlPullParser.getName();

					switch (eventType) {
					// 文档开始
					case XmlPullParser.START_DOCUMENT:
						root = new ArrayList<String>();
						map = new HashMap<String, ArrayList<CityInfo>>();
						break;
					// 开始节点
					case XmlPullParser.START_TAG:
						if ("key".equals(nodeName)) {

							mTemp = xmlPullParser.nextText();
							root.add(mTemp);
						} else if ("array".equals(nodeName)) {
							element = new ArrayList<CityInfo>();
						} else if ("string".equals(nodeName)) {
							cityInfo = new CityInfo();

							String str = xmlPullParser.nextText();
							String[] temp = str.split(":");
							cityInfo.name = temp[0];
							cityInfo.codeName = temp[1];
							cityInfo.pName = temp[2];
							cityInfo.shortName = temp[3];
							element.add(cityInfo);
						}
						break;
					// 结束节点
					case XmlPullParser.END_TAG:
						if ("array".equals(nodeName)) {
							map.put(mTemp, element);
							cityInfo = null;
						}
						break;
					default:
						break;
					}
					eventType = xmlPullParser.next();
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		}

	}
}
